function deepExtend(to, from) {
    for (let key in to) {
        try {
            var value = from[key]
            if(!value) continue
        } catch (error) {
            continue
        }
        if (typeof to[key] !== 'object' || to[key] === null){
            to[key] = value
        }else{
            deepExtend(to[key], value)
        }
    }
}

const id = Math.random() + new Date()
export const setWaterMark = (text, elOrSelecotr, option) =>{
    const bgEle = document.getElementById(id)
    if (bgEle) {
        document.body.removeChild(bgEle);
    }

    const useOption = {
        blockWdith: 150,
        blockHeight: 80,
        rotate: 20,
        font: "18px Vedana",
        fillStyle: '#666666',
        textAlign: 'center',
        textBaseline: 'middle',
        zIndex: 10000,
        opacity: '0.08'
    }
    deepExtend(useOption, option)
    console.log(useOption);
    const can = document.createElement("canvas");
    can.width = useOption.blockWdith;
    can.height = useOption.blockHeight;

    const cans = can.getContext("2d");
    cans.rotate((-useOption.rotate * Math.PI) / 180);
    cans.font = useOption.font
    cans.fillStyle = useOption.fillStyle
    cans.textAlign = useOption.textAlign
    cans.textBaseline = useOption.textBaseline
    cans.fillText(text, can.width / 2, can.height);


    const div = document.createElement("div");
    div.id = id
    div.style.pointerEvents = "none";
    div.style.opacity = useOption.opacity
    div.style.position = "absolute";
    div.style.top = 0
    div.style.left = 0
    div.style.right = 0
    div.style.bottom = 0
    div.style.zIndex = "100000";

    let element
    if(!elOrSelecotr){
        element = document.documentElement
    }else if(typeof elOrSelecotr === 'string'){
        element = document.querySelector(elOrSelecotr)
    }else {
        element = elOrSelecotr
    }
    div.style.background = "url(" + can.toDataURL("image/png") + ") left top repeat";
    element.style.position = 'relative'
    element.appendChild(div);
}

export const removeWaterMark = () =>{
    const bgEle = document.getElementById(id)
    bgEle && bgEle.remove()
}
